package edu.utdallas.alps.controllers;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;

/**
 * Servlet implementation class LoginServlet
 */
public class AuthenticationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthenticationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String pwd = request.getParameter("password");
		
		String userId = authenticateUser(email, pwd);
		System.out.println(email + " " + pwd);
		if(userId != null){
			HttpSession session = request.getSession();
			session.setAttribute("userid", userId );
			System.out.println("here...");
		response.sendRedirect("shop/loginsuccess");
		}else{
			System.out.println("not authenticated");
			response.sendRedirect("autherror");
		}
	}

	private String authenticateUser(String email, String pwd) {
		String userId = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore",
					"bkadmin", "nozama");
			Statement stmt = conn.createStatement();
			String query = "select customer_id from customers where customer_email='" + email + "' and " +
			"customer_password='" + pwd +"';";
			ResultSet rs = stmt.executeQuery(query);
			while(rs.next()){
				userId = rs.getString("customer_id");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return userId;
	}

}
